//
//  SearchController.m
//  takeout
//
//  Created by Mac on 12-5-16.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SearchController.h"
#define addComponent 0
#define typeComponent 1
#define timeComponent 2
#import "SearchShopListController.h"
#import "SupplierCategory.h"

@implementation SearchController
@synthesize searchSupplierCategories;

- (void)viewDidLoad
{   
    currentPage=1;
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
	manager=[[SupplierManager alloc]init];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"001s.png"] forBarMetrics: UIBarMetricsDefault];
    self.title=@"索搜";
    self.view.backgroundColor=[UIColor groupTableViewBackgroundColor];
    //设置背景按钮
    UIButton *bgBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    bgBtn.frame=CGRectMake(0,0,320, 460);
    [bgBtn addTarget:self action:@selector(cancelInput:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bgBtn];
    //设置搜索按钮背景
    UIImageView *topView=[[UIImageView alloc]init];
    topView.frame=CGRectMake(0,-4,320, 37);
    [topView setImage:[UIImage imageNamed:@"searchBg6.png"]];  
    [topView setUserInteractionEnabled:YES];  
    [self.view addSubview:topView];
    [topView release];
    //设置搜索按钮
    directBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    directBtn.frame=CGRectMake(0, -4, 159, 37);
    [directBtn setTitle:@"直接索搜" forState:UIControlStateNormal];
    directBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
    [directBtn setBackgroundImage:[UIImage imageNamed:@"searchBg7.png"] forState:UIControlStateNormal];
    [directBtn setBackgroundImage:[UIImage imageNamed:@"searchBg5.png"] forState:UIControlStateSelected];
    directBtn.selected=YES;
    [directBtn addTarget:self action:@selector(directSearch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:directBtn];
    detailBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    detailBtn.frame=CGRectMake(159, -4, 159, 37);
    [detailBtn setTitle:@"进阶索搜" forState:UIControlStateNormal];
    detailBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
    [detailBtn setBackgroundImage:[UIImage imageNamed:@"searchBg2.png"] forState:UIControlStateNormal];
    [detailBtn setBackgroundImage:[UIImage imageNamed:@"searchBg3.png"] forState:UIControlStateSelected];
    [detailBtn addTarget:self action:@selector(detailSearch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:detailBtn];
    
    //设置直接搜索内容背景
    directSearchView=[[UIView alloc]initWithFrame:CGRectMake(0,44, 320, 44)];
    [self.view addSubview:directSearchView];
    //设置直接搜索控件
    searchBarCustom = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 
    searchBarCustom.delegate=self;
    //移出原背景颜色
    UIView *segment=[searchBarCustom.subviews objectAtIndex:0];
    [segment removeFromSuperview];
    [directSearchView addSubview:searchBarCustom];
    
    //设置详细搜索内容背景
    detailSearchView=[[UIView alloc]initWithFrame:CGRectMake(0,90,320,230)];
    [self.view addSubview:detailSearchView];
    [detailSearchView setHidden:YES];
    //设置条件标题
    UILabel *addLbl=[[UILabel alloc]initWithFrame:CGRectMake(55,-20,45, 16)];
    [addLbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    [addLbl setBackgroundColor:[UIColor clearColor]];
    addLbl.text=@"地区";
    [detailSearchView addSubview:addLbl];
    [addLbl release];
    
    UILabel *typeLbl=[[UILabel alloc]initWithFrame:CGRectMake(140,-20,45, 16)];
    [typeLbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    [typeLbl setBackgroundColor:[UIColor clearColor]];
    typeLbl.text=@"类型";
    [detailSearchView addSubview:typeLbl];
    [typeLbl release];
    
    UILabel *timeLbl=[[UILabel alloc]initWithFrame:CGRectMake(215,-20,80, 16)];
    [timeLbl setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    [timeLbl setBackgroundColor:[UIColor clearColor]];
    timeLbl.text=@"营业时间";
    [detailSearchView addSubview:timeLbl];
    [timeLbl release];
    
    //设置pickerview
    conditionPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 12, 280, 200)];
    conditionPickerView.delegate = self;
    conditionPickerView.dataSource = self;
    conditionPickerView.showsSelectionIndicator = YES;
    [detailSearchView addSubview:conditionPickerView];
    [conditionPickerView release];
    //设置确定按钮
    searchBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame=CGRectMake(104, 210, 111, 30);
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"searchBg1.png"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(detailSearchList:) forControlEvents:UIControlEventTouchUpInside];
    [detailSearchView addSubview:searchBtn];
    
    //测试数据
    addTestData = [[NSArray alloc] initWithObjects:@"地区",@"市政府周边", @"步行街周边",@"狮标周边",@"鸳鸯池周边",@"华侨医院周边",@"服装城周边", nil];
    typeTestData= [[NSArray alloc] initWithObjects:@"类型",@"小吃",@"外卖",@"小吃",@"小吃",@"小吃",@"小吃",@"小吃", nil];
    timeTestData= [[NSArray alloc] initWithObjects:@"营业状况",@"营业中",@"打烊", nil];
    
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;	
    [super viewDidLoad];
}
//取消键盘
- (IBAction)cancelInput:(id)sender{
    [searchBarCustom resignFirstResponder];
}
//点击详细搜索进入商铺列表
-(IBAction)detailSearchList:(id)sender{
    NSString *isSelling = @"";
    if([address isEqualToString: @"地区"]){
        address = nil;
    }
    if([type isEqualToString:@"类型"]){
        type=nil;
    }
    
    if([time isEqualToString: @"营业中"]){
        isSelling = @"y";
    }
    else if([time isEqualToString: @"打烊"]){
        isSelling = @"n";
    }
    else{
        isSelling = nil;
    }
    
    NSLog(@"地区%@类型%@营业状态%@",address,type,isSelling);

    NSString *supplierCategoryTagString=[NSString stringWithFormat: @"%d", supplierCategoryId];
    NSString *currentPageString=[NSString stringWithFormat: @"%d", currentPage];
    
    if([appDelegate status]){
        //联网
        suppliers = [[manager getSupplier:[NSString stringWithFormat:@"%d",supplierCategoryId] pageIndex:currentPage road:address isSelling:isSelling] retain];
        //添加到本地
        [fmdbSupplierManager insertSupplierByCategoryId:suppliers supplierCategoryId:supplierCategoryTagString sPage:currentPageString];
    }
    else{
        //离线
        suppliers=[[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:supplierCategoryTagString sPage:currentPageString road:address isSelling:isSelling] retain];
    }
    if (suppliers == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
    }
    
    
    //创建新的试图并将试图推入栈中
    SearchShopListController *shopListController = [[SearchShopListController alloc]initWithNibName:@"ShopListController" bundle:nil];
    UINavigationController  *theNavController = [[UINavigationController alloc]
                                                 initWithRootViewController:shopListController];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:2];
    [dictionary setObject:suppliers forKey:@"Suppliers"];
    shopListController.supplierCategoryTag=supplierCategoryId;
    shopListController.address=address;
    shopListController.isSelling=isSelling;
    shopListController.searchType=@"1";//进入直接搜索
    [shopListController setRecieveDictionary:dictionary];
    [shopListController initMembers];
    [shopListController release];
    theNavController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController pushViewController: shopListController animated:YES];
    [theNavController release];


}



//点击直接搜索
-(IBAction)directSearch:(id)sender{
    directBtn.selected=YES;
    detailBtn.selected=NO;
    [directSearchView setHidden:NO];
    [detailSearchView setHidden:YES];
}
//点击详细搜索
-(IBAction)detailSearch:(id)sender{
    [searchBarCustom resignFirstResponder];
    directBtn.selected=NO;
    detailBtn.selected=YES;
    [directSearchView setHidden:YES];
    [detailSearchView setHidden:NO];
}





//返回有pickerview的组件数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

//返回每个组件上的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if(component==addComponent){
        return [addTestData count];     
    }
    if(component==typeComponent){
        NSArray *supplierCategories = [appDelegate.recieveDictionary objectForKey:@"SupplierCategories"];
        return [supplierCategories count];     
    }
    return [timeTestData count];     
}

//设置picker的值和字体大小
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *contentLbl = nil;      
    NSArray *supplierCategories = [appDelegate.recieveDictionary objectForKey:@"SupplierCategories"];
    SupplierCategory *supplierCategory=[supplierCategories objectAtIndex:row];
    if (component == addComponent) {
        
        contentLbl = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)] autorelease];
        contentLbl.textAlignment = UITextAlignmentCenter;
        contentLbl.font = [UIFont systemFontOfSize:14];
        contentLbl.text=[addTestData objectAtIndex:row];
        contentLbl.backgroundColor = [UIColor clearColor];
    }
    if(component==typeComponent){
        contentLbl = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)] autorelease];
        contentLbl.textAlignment = UITextAlignmentCenter;
        contentLbl.font = [UIFont systemFontOfSize:14];
        contentLbl.text=supplierCategory.supplierCategoryName;
        contentLbl.backgroundColor = [UIColor clearColor];
    }
    if(component==timeComponent){
        contentLbl = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)] autorelease];
        contentLbl.textAlignment = UITextAlignmentCenter;
        contentLbl.font = [UIFont systemFontOfSize:14];  
        contentLbl.text=[timeTestData objectAtIndex:row];
        contentLbl.backgroundColor = [UIColor clearColor];
    }
    return contentLbl;
}





//当你选中pickerview的某行时会调用该函数。
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSArray *supplierCategories = [appDelegate.recieveDictionary objectForKey:@"SupplierCategories"];
    SupplierCategory *supplierCategory=[supplierCategories objectAtIndex:row];
    if (component == addComponent) {
        address=[addTestData objectAtIndex:row];
    }
    
    if (component == typeComponent) {
        type=supplierCategory.supplierCategoryName;
        supplierCategoryId=supplierCategory.supplierCategoryId;
    }
    if (component == timeComponent) {
        time=[timeTestData objectAtIndex:row];
        
    }
}

//直接搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { 
    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    
    if([appDelegate status]){
        //        //联网状态
        //        suppliers=nil;
        
        //离线状态
        suppliers=[fmdbSupplierManager getSuppliersByNameOrDishAndPage:[searchBar text] sPage:@"1"];
        for(Supplier *supplier in suppliers){
            NSLog(@"快速的遍历数组对象为: %@ %@",supplier.supplierName,supplier.address);
        }
    }
    else{
        //离线状态
        suppliers=[fmdbSupplierManager getSuppliersByNameOrDishAndPage:[searchBar text] sPage:@"1"];
        for(Supplier *supplier in suppliers){
            NSLog(@"快速的遍历数组对象为: %@ %@",supplier.supplierName,supplier.address);
        }
    }
    if (suppliers == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        return;
    }
    //创建新的试图并将试图推入栈中
    SearchShopListController *shopListController = [[SearchShopListController alloc]initWithNibName:@"ShopListController" bundle:nil];
    UINavigationController  *theNavController = [[UINavigationController alloc]
                                                 initWithRootViewController:shopListController];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:1];
    
    
    [dictionary setObject:suppliers forKey:@"Suppliers"];
    shopListController.searchType=@"0";
    shopListController.conditions=[searchBar text];
    [shopListController setRecieveDictionary:dictionary];
    [shopListController initMembers];
    [shopListController release];
    theNavController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController pushViewController: shopListController animated:YES];
    [theNavController release];
}
- (void)dealloc {
    if (manager!=nil) {
        [manager release];
    }
}

@end
